import socketserver
import struct
import json
import os


server_dir = r'E:\python_program\老男孩笔记\day28网络编程\local_dir'


class Myserver(socketserver.BaseRequestHandler):
    def my_recv(self,encoding='utf-8'):
        dic_len = self.request.recv(4)
        dic_len = struct.unpack('i', dic_len)[0]
        dic = self.request.recv(dic_len).decode(encoding)
        dic = json.loads(dic)
        return dic

    def my_send(self,dic,encoding='utf-8'):
        str_dic = json.dumps(dic)  # 字典转json
        dbic = str_dic.encode(encoding)  # str转bytes
        dic_len = len(dbic)  # 计算bytes长度
        bytes_len = struct.pack('i', dic_len)
        self.request.send(bytes_len)
        self.request.send(dbic)

    def send_file(self,dic,file_path):
        with open(file_path, 'rb') as f:
            while dic['filesize'] > 2048:
                content = f.read(2048)
                self.request.send(content)
                dic['filesize'] -= len(content)
            else:
                content = f.read()
                self.request.send(content)

    def download(self,dic):
        filename = dic['filename']
        file_path = os.path.join(server_dir, filename)

        dic = {}
        if os.path.isfile(file_path):
            dic['filesize'] = os.path.getsize(file_path)
            dic['isfile'] = True
            self.my_send(dic)
            self.send_file(dic, file_path)

        else:
            dic['isfile'] = False
            self.my_send(dic)


    def handle(self):
        dic = self.my_recv()
        if dic['oprate'] == 'download':
            self.download(dic)






server = socketserver.ThreadingTCPServer(('127.0.0.1', 9000), Myserver)
server.serve_forever()
